
from django.conf import settings
from django.shortcuts import render
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings
# Create your views here.
from rest_framework import status

from rest_framework.generics import GenericAPIView ,CreateAPIView
from rest_framework.response import Response

from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ


# http://api.meiduo.site:8000/oauth/qq/authorization/
# url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
from rest_framework_jwt.settings import api_settings

from oauth import serializers
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQSerializer


class QQAuthURLView(APIView):
    """QQ登录跳转接口"""
    """提供QQ登录页面网址
       https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&state=xxx
    """

    def get(self, request):

        # next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next = request.query_params.get('next')
        if not next:
            next = '/'

        # 获取QQ登录页面网址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        # 创建工具对象

        login_url = oauth.get_qq_url()

        return Response({'login_url': login_url})


# url(r'^qq/user/$', views.QQAuthUserView.as_view()),
class QQAuthUserView(GenericAPIView):
    """用户扫码登录的回调处理"""

    # 指定序列化器
    # serializers_class = serializers.QQAuthUserSerializer
    def get(self, request):
        code = request.query_params.get('code')
        if not code:
            return Response({'message': 'code返回值错误'}, status=400)

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)

        except Exception:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 使用openid查询该QQ用户是否在美多商城中绑定过用户
        try:
            # 能查询的, 就证明是已经绑定的了

            oauth_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            # get没有查询到的时候, 会报异常. 到这边则证明没有查询到. 没有绑定
            # 这边还有返回一个token 里面还要包含openid返回给前端 因为这边要跳转到别的地方去, 注册的时候 需要要用到openid的值
            tjs = TJS(settings.SECRET_KEY, 300)
            data = {'openid': openid}
            access_token = tjs.dumps(data).decode()
            return Response({'access_token': access_token})

        # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        user = oauth_user.user
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'access_token': token,
            'username': user.username,
            'user_id': user.id,
        })

    def post(self, request):
        data = request.data
        # 反序列化过程
        ser = OAuthQQSerializer(data=data)
        # 用序列化器校验传递过来的参数
        ser.is_valid()
        user = ser.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'token': token,
            'id': user.id,
            'username': user.username
        })

